package com.lap.framework.validate.validator;

import com.lap.framework.validate.annotation.FieldMatch;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

import java.lang.reflect.Field;

public class FieldMatchValidator implements ConstraintValidator<FieldMatch, Object> {
  private String sourceField;
  private String targetField;
  private String message;

  @Override
  public void initialize(FieldMatch constraintAnnotation) {
    this.sourceField = constraintAnnotation.sourceField();
    this.targetField = constraintAnnotation.targetField();
    this.message = constraintAnnotation.message();
  }

  @Override
  public boolean isValid(Object value, ConstraintValidatorContext context) {
    try {
      Object sourceValue = getFieldValue(value, sourceField);
      Object targetValue = getFieldValue(value, targetField);

      boolean valid =
          (sourceValue == null && targetValue == null)
              || (sourceValue != null && sourceValue.equals(targetValue));

      if (!valid) {
        context.disableDefaultConstraintViolation();
        context
            .buildConstraintViolationWithTemplate(message)
            .addPropertyNode(targetField)
            .addConstraintViolation();
      }
      return valid;
    } catch (Exception e) {
      return false;
    }
  }

  private Object getFieldValue(Object object, String fieldName) throws Exception {
    Field field = object.getClass().getDeclaredField(fieldName);
    field.setAccessible(true);
    return field.get(object);
  }
}
